<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import type { FormSubmitEvent, Form } from "@nuxt/ui";
import {
  userCreateSchema,
  type UserCreateInput,
} from "~~/shared/schemas/user.schema";

const toast = useToast();
const router = useRouter();

const roles = [
  { label: "管理员", value: "admin" },
  { label: "普通用户", value: "user" },
];

const getInitialState = (): UserCreateInput => ({
  username: "",
  email: "",
  role: "user",
});

// Form state
const state = reactive(getInitialState());

const loading = ref(false);
const formRef = ref<Form<UserCreateInput> | null>(null); // Use imported type here too

// Function to reset the form
const resetForm = () => {
  formRef.value?.clear();
  Object.assign(state, getInitialState());
};

// Handle form submission - Use imported type for event
async function onSubmit(event: FormSubmitEvent<UserCreateInput>) {
  loading.value = true;
  try {
    // Use $fetch as per previous user change
    await $fetch("/api/user", {
      method: "POST",
      body: event.data,
    });

    toast.add({
      title: "用户创建成功",
      color: "success",
      icon: "i-lucide-check-circle",
    });
    router.push("/system/user");
  } catch (err: any) {
    // Enhance error handling for $fetch (might throw different error structure)
    const errorMessage =
      err.data?.message || err.statusMessage || err.message || "创建用户失败";
    toast.add({
      title: "创建用户失败",
      description: errorMessage,
      color: "error",
      icon: "i-lucide-alert-circle",
    });
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div class="p-4">
    <div class="flex items-center mb-4">
      <UButton
        icon="i-lucide-arrow-left"
        variant="ghost"
        color="neutral"
        class="mr-2"
        aria-label="返回"
        @click="router.back()"
      />
      <h1 class="text-2xl font-bold">创建新用户</h1>
    </div>
    <UCard>
      <UForm
        ref="formRef"
        :schema="userCreateSchema"
        :state="state"
        class="space-y-4"
        @submit.prevent="onSubmit"
      >
        <UFormField label="用户名" name="username" required>
          <UInput v-model="state.username" placeholder="请输入用户名" />
        </UFormField>

        <UFormField label="邮箱" name="email" required>
          <UInput
            v-model="state.email"
            type="email"
            placeholder="请输入邮箱地址"
          />
        </UFormField>

        <UFormField label="角色" name="role" required>
          <USelect
            v-model="state.role"
            :items="roles"
            value-attribute="value"
            option-attribute="label"
          />
        </UFormField>
        <div class="flex justify-end space-x-2">
          <UButton
            type="button"
            variant="outline"
            :disabled="loading"
            @click="resetForm"
          >
            重置
          </UButton>
          <UButton type="submit" :loading="loading"> 创建用户 </UButton>
        </div>
      </UForm>
    </UCard>
  </div>
</template>
